/*
This file is part of lAPIn.

lAPIn is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

lAPIn is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with lAPIn.  If not, see <http://www.gnu.org/licenses/>.
*/
package org.opensource.nabaztag.util;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.LinkedList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.opensource.nabaztag.Message;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * Helper class facilitating XML data extraction.
 */
public class XMLUtil {

    private XMLUtil() {
    }

    /**
     * Extracts the response XML element from received result.
     *
     * @param result the whole result received
     * @return the rsp XML element
     */
    public static Element extractResponse(final String result) {
        try {
            final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            final DocumentBuilder db = dbf.newDocumentBuilder();
            final Document doc = db.parse(new InputSource(new StringReader(result)));
            final Element rspElement = doc.getDocumentElement();
            rspElement.normalize();
            return rspElement;
        } catch (Exception e) {
           throw new RuntimeException("Failed to convert response to XML document", e);
        }
    }

    /**
     * Extracts the message node from Nabaztag response.
     *
     * @param result full Nabaztag response
     * @return message node
     */
    public static Message extractResponseMessage(final String result) {
        final String message = extractResponse(result).getElementsByTagName("message").item(0).getTextContent();
        return Message.valueOf(message);
    }

    /**
     * Extracts the comment node from Nabaztag response.
     *
     * @param result full Nabaztag response
     * @return comment node
     */
    public static String extractResponseComment(final String result) {
        return extractResponse(result).getElementsByTagName("comment").item(0).getTextContent();
    }

    /**
     * Returns the value of the first Node of provided Element.
     *
     * @param element element used to navigate
     * @return value of first Node of provided Element
     */
    public static String extractFirstNodeValue(final Element element) {
        return element.getChildNodes().item(0).getTextContent();
    }

    /**
     * Returns the value of the first Node of provided Element.
     *
     * @param element element used to navigate
     * @return value of first Node of provided Element
     */
    public static List<String> extractNodeAttributes(final Element element, final String attributeName) {
        final List<String> attributes = new LinkedList<String>();

        final NodeList childNodes = element.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            final Node node = childNodes.item(i);
            final Node attribute = node.getAttributes().getNamedItem(attributeName);
            if (attribute != null) {
                attributes.add(attribute.getNodeValue());
            }
        }
        return attributes;
    }

    /**
     * Converts a XML Node into a String representation.
     *
     * @param node node to be represented as a String
     * @return the String representation of this ode
     */
    public static String toString(final Node node) {
        final StringWriter stringWriter = new StringWriter();
        final StreamResult streamResult = new StreamResult(stringWriter);
        try{
            final Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.transform(new DOMSource(node),streamResult);
        } catch(Exception e) {
        }
        return stringWriter.toString();
    }

}
